package com.ashafa.server;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.HttpHeaders;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.Request;
import org.mortbay.util.ByteArrayISO8859Writer;
import org.mortbay.log.Log;
import org.mortbay.util.IO;
import org.mortbay.jetty.HttpMethods;


import org.mortbay.jetty.handler.*;



public class CustomDefaultHandler extends DefaultHandler{
	 long _faviconModified = (System.currentTimeMillis() / 1000) * 1000;
	 byte[] _favicon;
	 boolean _serveIcon=true;
	 
	 
	public CustomDefaultHandler()
	{
		try
        {
            URL fav = this.getClass().getClassLoader().getResource("com/ashafa/server/favicon.ico");
            if (fav!=null)
            _favicon = IO.readBytes(fav.openStream());
        }
        catch(Exception e)
        {
            Log.warn(e);
        }
	}
	
	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException
	{
		Request base_request = request instanceof Request ? (Request)request : HttpConnection.getCurrentConnection().getRequest();
        
		if (response.isCommitted() || base_request.isHandled())
		   return;
		
		base_request.setHandled(true);
		
		String method = request.getMethod();
		
		// little cheat for common request
		if(_serveIcon && _favicon != null && method.equals(HttpMethods.GET) && request.getRequestURI().equals("/favicon.ico"))
		{
			if (request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)==_faviconModified)
				response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			else
			{
				response.setStatus(HttpServletResponse.SC_OK);
				response.setContentType("image/x-icon");
				response.setContentLength(_favicon.length);
				response.setDateHeader(HttpHeaders.LAST_MODIFIED, _faviconModified);
				response.getOutputStream().write(_favicon);
		    }
			return;
		}
		
		if(!method.equals(HttpMethods.GET) || !request.getRequestURI().equals("/"))
		{
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		
		 
		ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
		
		writer.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n");
		writer.write("<title>You are now running ashafa.</title>\n");
		writer.write(" <style type=\"text/css\"> \n" + 
			    "body { background-color: #fff; color: #333; } \n\n" + 
			    "body, p, ol, ul, td { \n" + 
			    "  font-family: verdana, arial, helvetica, sans-serif; \n" + 
			    "  font-size:   13px; \n" + 
			    "  line-height: 18px; \n" + 
			    "}\n\n" + 
			    "pre { \n" + 
			    "  background-color: #eee; \n" + 
			    "  padding: 10px; \n" + 
			    "  font-size: 11px; \n" + 
			    "}\n\n" + 
			    "a { color: #000; } \n" + 
			    "a:visited { color: #666; } \n" + 
			    "a:hover { color: #fff; background-color:#000; } \n" + 
			  	"</style>");
		writer.write("</head>\n<body>\n\n");
		writer.write("<h1>You are now running ashafa.</h1>\n");
		writer.write("<p>Contexts known to this server are:</p>\n<ul>\n");
		
		Server server = getServer();
		
		Handler[] handlers = (server == null) ? null : server.getChildHandlersByClass(ContextHandler.class);
		
		for(int i=0;handlers!=null && i<handlers.length;i++)
		{
			ContextHandler context = (ContextHandler)handlers[i];
			if(context.isRunning() && (!context.getContextPath().equals("/") && !context.getContextPath().equals("/static")))
			{
				writer.write("<li><a href=\"");
		  if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
		     writer.write("http://"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
		  writer.write(context.getContextPath());
		  if (context.getContextPath().length()>1 && context.getContextPath().endsWith("/"))
		   writer.write("/");
		  writer.write("\">");
		  writer.write(context.getContextPath());
		  writer.write("</a></li>\n");
		   }
		  
		}
		writer.write("</ul>\n");    
		
		   writer.write("\n</body>\n</html>\n");
		  writer.flush();
		   response.setContentLength(writer.size());
		 OutputStream out=response.getOutputStream();
		  writer.writeTo(out);
		  out.close();
		
		 return;
    }
	
	
}
